
/**
 * 初始化参数
 */
//#ifdef APP-PLUS
var Socket = plus.android.importClass("java.net.Socket");
var socket;
var outputStream;
//解决高低版本兼容
var StrictMode = plus.android.importClass("android.os.StrictMode");
var Build = plus.android.importClass("android.os.Build");
//#endif
/**
 * 构造对象
 */
var wifiPrint = {
	checkWifi(){
		return new Promise((resolve,reject)=>{
			uni.startWifi({
				success() {						
					uni.getConnectedWifi({
						partialInfo:true,
						success(info) {
							if(info?.wifi?.SSID.indexOf('IT4') < 0 && info?.wifi?.SSID.indexOf('TP-LINK_B70F') < 0){
								uni.showToast({
									title:'请连接打印机wifi',
									icon:'none',
									duration:2000
								})
								resolve(false)
								return;
							}
							
							resolve(info?.wifi?.SSID)
						},
						fail() {
							uni.showToast({
								title:'获取当前连接wifi失败，请重试',
								icon:'none'
							})
							resolve(false)
						}
				    })
				},
				fail() {
					uni.showToast({
						title:'请连接打印机wifi',
						icon:'none',
						duration:2000
					})
					resolve(false)
				}
			})
	    })
	},
	connectWifi(ip, port) {
		return new Promise((resolve)=>{
			if (Build.VERSION.SDK_INT > 9) {
				var policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
				StrictMode.setThreadPolicy(policy);
			}
			try {
				socket = new Socket(ip, port);
				socket.setKeepAlive(true);
				socket.setSoTimeout(5000);
				outputStream = socket.getOutputStream();
				plus.android.importClass(outputStream);
				// uni.showToast({
				// 	title: 'wifi连接成功',
				// });
				resolve(true)
			} catch (e) {
				uni.showToast({
					title: 'wifi连接超时，请重新连接！',
					icon:'none'
				});
				resolve(false)
			}
		})

	},
	getWifiList(){
		uni.startWifi({
			success() {
				uni.getWifiList({});
				uni.onGetWifiList((wifiList)=>{
					console.log(wifiList)
				})
			}
		})
	},
	sendData(data) {
		outputStream.write(data);
		outputStream.flush();
		// 关闭socket
		socket.shutdownOutput();
		console.log(socket);
	}
}

export default wifiPrint
